package com.example.admin;

import com.example.admin.service.NotificationService;
import de.codecentric.boot.admin.server.domain.entities.Instance;
import de.codecentric.boot.admin.server.domain.entities.InstanceRepository;
import de.codecentric.boot.admin.server.domain.events.InstanceEvent;
import de.codecentric.boot.admin.server.domain.values.StatusInfo;
import de.codecentric.boot.admin.server.notify.AbstractEventNotifier;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.concurrent.CompletableFuture;

/**
 * @author kaka
 */
@Slf4j
@Component
@Order(1) // 通知顺序
public class MultiChannelNotifier extends AbstractEventNotifier {

    @Resource
    private NotificationService notificationService;

    public MultiChannelNotifier(InstanceRepository repository) {
        super(repository);
    }

    @Override
    protected Mono<Void> doNotify(InstanceEvent event, Instance instance) {
        log.info("[MultiChannelNotifier] {}", event);
        log.info("[MultiChannelNotifier] {}", instance.getStatusInfo().getStatus());
        if (StatusInfo.STATUS_OFFLINE.equals(instance.getStatusInfo().getStatus())) {
            // 异步发送通知
            CompletableFuture.runAsync(() -> {
                notificationService.sendMsgNotification(instance.getStatusInfo().getStatus()
                        , instance.getRegistration().getName()
                        , instance.getRegistration().getServiceUrl());

            });
        } else if (StatusInfo.STATUS_UP.equals(instance.getStatusInfo().getStatus())) {
            // 异步发送通知
            CompletableFuture.runAsync(() -> {
                notificationService.sendMsgNotification(instance.getStatusInfo().getStatus()
                        , instance.getRegistration().getName()
                        , instance.getRegistration().getServiceUrl());

            });
        }
        return Mono.empty();
    }


}
